package com.youlu.campus.web.community.service.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.base.ContentTypeEnum;
import com.youlu.campus.base.base.InteractiveActionEnum;
import com.youlu.campus.base.community.ContentTopicBase;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.community.dto.InteractiveMqRequest;
import com.youlu.campus.web.community.dto.TopicCountResponse;
import com.youlu.campus.web.community.dto.TopicQueryRequest;
import com.youlu.campus.web.community.dto.TopicUserResponse;
import com.youlu.campus.web.community.dto.TopicVoteRequest;
import com.youlu.campus.web.community.entity.TopicCount;
import com.youlu.campus.web.community.entity.TopicInfo;
import com.youlu.campus.web.community.service.TopicCountService;
import com.youlu.campus.web.common.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 话题与用户统计接口实现类
 *
 * @author: YangJ
 * @date: 2020/11/25 17:39
 */
@Slf4j
@Service("topicCountService")
public class TopicCountServiceImpl extends BaseService implements TopicCountService {


//    @Autowired
//    private MQService mqService;

    @Override
    public TopicCountResponse queryTopicCountPercent(String topicId) {

        Query query = new Query();
        query.addCriteria(Criteria.where("topicId").is(topicId));
        query.addCriteria(Criteria.where("selectValue").is("A"));
        long a = mongoTemplate.count(query, TopicCount.class);

        query = new Query();
        query.addCriteria(Criteria.where("topicId").is(topicId));
        query.addCriteria(Criteria.where("selectValue").is("B"));
        long b = mongoTemplate.count(query, TopicCount.class);

        TopicCountResponse response = new TopicCountResponse();
        long all = a + b;
        if (all > 0) {
            response.setPkAPercent(CommonUtils.percnet(a, all));
            response.setPkBPercent(CommonUtils.percnet(b, all));
        } else {
            response.setPkAPercent("50%");
            response.setPkBPercent("50%");
        }
        return response;
    }

    @Override
    public TopicCount queryUserVoted(String topicId) {

        UserPO user = RequestContext.getCurUser();
        Query query = new Query();
        query.addCriteria(Criteria.where("voted").is(true));
        query.addCriteria(Criteria.where("topicId").is(topicId));
        query.addCriteria(Criteria.where("userId").is(user.getId()));

        return mongoTemplate.findOne(query, TopicCount.class);
    }

    @Override
    public TopicCountResponse vote(TopicVoteRequest request) {
        log.info(":>>> 开始投票处理:{}", JSON.toJSONString(request));
        UserPO user = RequestContext.getCurUser();
        Query query = new Query().addCriteria(Criteria.where("topicId").is(request.getTopicId()).and("userId").is(user.getId()));
        boolean exist = mongoTemplate.exists(query, TopicCount.class);
        if (!exist) {
            TopicCount topicCount = mapperFacade.map(request, TopicCount.class);
            topicCount.setVoted(true);
            topicCount.setUserId(user.getId());
            topicCount.setUpdatedTime(new Date());
            mongoTemplate.insert(topicCount);
            //维护话题统计信息-热度数(+1)
            InteractiveMqRequest req = new InteractiveMqRequest();
            req.setType(ContentTypeEnum.HT.getCode());
            req.setAction(InteractiveActionEnum.HOT.getCode());
            req.setBid(request.getTopicId());
            req.setValue(1);
//            mqService.sendNormal(req, CampusMQDefinition.ROUTING_KEY_INTERACTIVE);
        }
        TopicCountResponse response = queryTopicCountPercent(request.getTopicId());


        return response;
    }

    @Override
    public boolean create(List<ContentTopicBase> topics) {
        if (topics != null && topics.size() > 0) {
            for (ContentTopicBase topicBase : topics) {
                create(topicBase.getTopicId());
            }
        }
        return true;
    }

    private void create(String topicId) {

        UserPO user = RequestContext.getCurUser();
        Query query = new Query();
        query.addCriteria(Criteria.where("topicId").is(topicId));
        query.addCriteria(Criteria.where("userId").is(user.getId()));
        TopicCount tc = mongoTemplate.findOne(query, TopicCount.class);
        if (tc == null) {
            TopicCount topicCount = new TopicCount();
            topicCount.setTopicId(topicId);
            topicCount.setUserId(user.getId());
            topicCount.setUpdatedTime(new Date());
            mongoTemplate.insert(topicCount);

            //维护话题统计信息-参与人数(+1)
            InteractiveMqRequest req = new InteractiveMqRequest();
            req.setType(ContentTypeEnum.HT.getCode());
            req.setAction(InteractiveActionEnum.JOIN.getCode());
            req.setBid(topicId);
            req.setValue(1);
//            mqService.sendNormal(req, CampusMQDefinition.ROUTING_KEY_INTERACTIVE);

        } else {
            tc.setUpdatedTime(new Date());
            mongoTemplate.save(tc);
        }
        //维护话题统计信息-动态数(+1)
        InteractiveMqRequest req = new InteractiveMqRequest();
        req.setType(ContentTypeEnum.HT.getCode());
        req.setAction(InteractiveActionEnum.CONTENT.getCode());
        req.setBid(topicId);
        req.setValue(1);
//        mqService.sendNormal(req, CampusMQDefinition.ROUTING_KEY_INTERACTIVE);

    }


    @Override
    public Page<TopicUserResponse> topicUser(TopicQueryRequest request) {

        //查询关联的话题信息
        UserPO user = RequestContext.getCurUser();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getId()));
        long count = mongoTemplate.count(query, TopicCount.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "updatedTime"));
        Sort sort = Sort.by(Sort.Direction.DESC, "updatedTime");
        query.with(sort);
        List<TopicCount> topicCounts = mongoTemplate.find(query.with(pageRequest), TopicCount.class);

        List<TopicUserResponse> list = topicCounts.stream().map(topicCount -> {
            TopicUserResponse response = new TopicUserResponse();
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("id").is(topicCount.getTopicId()));
            TopicInfo topicInfo = mongoTemplate.findOne(query1, TopicInfo.class);
            if (topicInfo != null) {
                mapperFacade.map(topicInfo, response);
                response.setHotValue(CommonUtils.intChange2Str(topicInfo.getHotCount(), "热度"));
                response.setDiscussValue(CommonUtils.intChange2Str(topicInfo.getCommentCount(), "讨论"));
                response.setSubTitle(topicInfo.getSubTitle());
            }
            if (StringUtils.isBlank(response.getDiscussValue())) {
                response.setDiscussValue("0讨论");
            }
            if (StringUtils.isBlank(response.getHotValue())) {
                response.setHotValue("0热度");
            }
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }
}
